package com.ark.frigate.spring.publisher;

import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.Map;

import org.apache.commons.lang3.builder.ToStringBuilder;
import org.springframework.context.event.EventListener;

import com.ark.frigate.spring.envet.MessageEvent;
import com.ark.frigate.spring.listener.MessageEventListener;

import lombok.extern.slf4j.Slf4j;

/**
 * 事件分发
 *
 * @author zengweilong
 */
@Slf4j
public class MessageEventPublisher {

    @EventListener
    public void publishEvent(MessageEvent messageEvent) {
        try {

            log.info("事件监听,参数:{}", ToStringBuilder.reflectionToString(messageEvent.getEntity()));

            if (null == messageEvent.getEntity()) {
                log.error("消息数据为空,不做处理");
                return;
            }

            Map<String, MessageEventListener> map =
                    BusinessEventPublisher.getContext().getBeansOfType(MessageEventListener.class);
            Object entity = messageEvent.getEntity();
            map.keySet().stream().forEach(k -> {
                MessageEventListener handler = map.get(k);
                Type type = handler.getClass().getGenericInterfaces()[0];
                Type argument = ((ParameterizedType) type).getActualTypeArguments()[0];
                if (argument.equals(entity.getClass())) {
                    handler.reviveMessage(messageEvent.getEntity());
                }
            });

        } catch (Exception e) {
            log.error("事件监听异常:{}", messageEvent, e);
        }
    }
}
